package utils

import (
	"fmt"
	"sort"
	"time"
)

//同一类型值的map排序
func SortMap(data map[string]interface{}, isDesc ...bool) []map[string]interface{} {
	var list []map[string]interface{}
	for k, v := range data {
		item := make(map[string]interface{})
		item[k] = v
		list = append(list, item)
	}

	sort.Slice(list, func(i, j int) bool {
		var val1 interface{}
		for _, v := range list[i] {
			val1 = v
			break
		}
		var val2 interface{}
		for _, v := range list[j] {
			val2 = v
			break
		}

		desc := true
		if isDesc != nil {
			desc = isDesc[0]
		}

		flag := false
		switch val1.(type) {
		case int:
			flag = If(desc, val1.(int) > val2.(int), val1.(int) < val2.(int)).(bool)
		case int32:
			flag = If(desc, val1.(int32) > val2.(int32), val1.(int32) < val2.(int32)).(bool)
		case int64:
			flag = If(desc, val1.(int64) > val2.(int64), val1.(int64) < val2.(int64)).(bool)
		case float32:
			flag = If(desc, val1.(float32) > val2.(float32), val1.(float32) < val2.(float32)).(bool)
		case float64:
			flag = If(desc, val1.(float64) > val2.(float64), val1.(float64) < val2.(float64)).(bool)
		default:
			fmt.Println(111)
		}
		return flag
	})
	return list
}

//map数组排序
func SortMapsByKey(data []map[string]interface{}, key string, isDesc ...bool) {
	sort.Slice(data, func(i, j int) bool {
		if _, ok := data[i][key]; !ok {
			return false
		}
		val1 := data[i][key]

		if _, ok := data[j][key]; !ok {
			return false
		}
		val2 := data[j][key]

		desc := true
		if isDesc != nil {
			desc = isDesc[0]
		}

		flag := false
		switch val1.(type) {
		case int:
			flag = If(desc, val1.(int) > val2.(int), val1.(int) < val2.(int)).(bool)
		case int32:
			flag = If(desc, val1.(int32) > val2.(int32), val1.(int32) < val2.(int32)).(bool)
		case int64:
			flag = If(desc, val1.(int64) > val2.(int64), val1.(int64) < val2.(int64)).(bool)
		case float32:
			flag = If(desc, val1.(float32) > val2.(float32), val1.(float32) < val2.(float32)).(bool)
		case float64:
			flag = If(desc, val1.(float64) > val2.(float64), val1.(float64) < val2.(float64)).(bool)
		case string:
			flag = If(desc, val1.(string) > val2.(string), val1.(string) < val2.(string)).(bool)
		case time.Time:
			flag = If(desc, (val1.(time.Time)).Unix() > (val2.(time.Time)).Unix(), (val1.(time.Time)).Unix() < (val2.(time.Time)).Unix()).(bool)
		default:
			flag = false
		}
		return flag
	})
}
